package com.pervasive.geo_tag.servlets;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pervasive.geo_tag.server.Note;
import com.pervasive.geo_tag.server.Photo;

/**
 * Servlet implementation class SaveServlet
 */
@WebServlet("/SaveServlet")
public class SaveServlet extends HttpServlet implements Serializable{
	
	private static final long serialVersionUID = 1L;
	private static final String SERVER_REPO = "C:\\Users\\mediaworld\\workspaceReti\\GeoTagWebService\\WebContent\\";
	private static final String SERVER_ADDRESS = "http://79.9.143.152:8081/GeoTagWebService/";
	private String photoFileName = "";
	private String locForFileName;

 
    public SaveServlet() {
        super();
    }

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
	
		Statement stmt = null;
		String dbName = "android_geo_tag";
		String queryPhoto;
		String queryNote;
		Connection con = null;
		String modNote = null;
		String id_photo = null;
	    ResultSet rs = null;
		Photo photo = new Photo();

		
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (InstantiationException e3) {
			e3.printStackTrace();
		} catch (IllegalAccessException e3) {
			e3.printStackTrace();
		} catch (ClassNotFoundException e3) {
			e3.printStackTrace();
		}
		try {
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/android_geo_tag", "root", "seppiessa");
		} catch (SQLException e1) {e1.printStackTrace();}
		try {
			stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
		} catch (SQLException e1) {e1.printStackTrace();}
		
		modNote = request.getParameter("note");
		id_photo = request.getParameter("id_photo");
	
		
		queryPhoto = "select * from " + dbName + ".photo where id_photo = " + id_photo ;
		
		try {
			rs = stmt.executeQuery(queryPhoto);
		} catch (SQLException e1) {e1.printStackTrace();}
		
		try {
			while(rs.next()){
				photo.setId_photo(rs.getInt("ID_PHOTO"));
				photo.setUri_photo(rs.getString("URI"));
				photo.setData(rs.getString("DATA"));
				photo.setSize(rs.getLong("SIZE"));
				photo.setId_note(rs.getInt("ID_NOTE"));
				photo.setLocation(rs.getString("LOCATION"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		queryNote = "update " + dbName + ".note set text='"+ modNote + "' where id_note = " + photo.getId_note();
		
		try {
			stmt.executeUpdate(queryNote);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
			Statement stmt = null;
			String dbName = "android_geo_tag";
			String queryPhoto;
			String queryNote;
			String location;
			Connection con = null;
			Note note = new Note();
			Photo photo = new Photo();
			
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
			} catch (InstantiationException e3) {e3.printStackTrace();} 
			  catch (IllegalAccessException e3) {e3.printStackTrace();} 
			  catch (ClassNotFoundException e3) {e3.printStackTrace();}
			  
			try {
				con = DriverManager.getConnection("jdbc:mysql://localhost:3306/android_geo_tag", "root", "seppiessa");
			} catch (SQLException e1) {e1.printStackTrace();}
			
			try {
				stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
			} catch (SQLException e1) {e1.printStackTrace();}
			
			
			
			try {
				photo.setId_photo(idPhotoGen());
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			photo.setData(request.getHeader("Date"));
			photo.setLocation(request.getHeader("Location"));
			System.out.println(photo.getLocation());
			photo.setSize(Long.parseLong(request.getHeader("Size")));
			locForFileName = photo.getLocation();
			location =  photo.getLocation().replace(" ", "+");
			location = location.toLowerCase();
			photoFileName = locForFileName + "_" + photo.getId_photo() + ".jpeg"; 
			photoFileName = photoFileName.replace(" ", "");

			
			try {
				  photo.setUri_photo(SERVER_ADDRESS +photoFileName);
			} catch (Exception e2) {e2.printStackTrace();}
			
			note.setText(request.getHeader("Note"));
			
			try {
				note.setId_note(idGenComm());
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
			photo.setId_note(note.getId_note());
			if(note.getText() == "null" || note.getText() == "")
				note.setText(" ");
			
			byte[] b = new byte[8192];

			InputStream in = request.getInputStream();	
			File f = new File(SERVER_REPO + photoFileName);
				
			FileOutputStream fos =  new FileOutputStream(f);
		    FileDescriptor fd = fos.getFD();
		    long size =  photo.getSize();
		    int readBytes = 0;
			for(long counter =  0; counter <  size; ){	
				readBytes = in.read(b);
				fos.write(b, 0, readBytes);
				counter += readBytes;
				}
			
			fos.flush();
			fd.sync();
			fos.close();
			in.close();

			queryNote = "insert into " + dbName + ".note values (" + 
						 note.getId_note() + ",'" + 
						 note.getText() +"')";
		
		  
		try {
			stmt.execute(queryNote);
			} catch (SQLException e) {e.printStackTrace();}
		
				queryPhoto = "insert into " + dbName + ".photo values (" + 
								photo.getId_photo() + "," + 
								photo.getId_note() +",'" + 
								photo.getUri_photo() + "',"+ 
								photo.getSize() +",'" + 
								photo.getData() + "','" + 
								location + "')";
		
			try {
				stmt.executeUpdate(queryPhoto);
				} catch (SQLException e) {e.printStackTrace();}
		
		
		
	}

	private int idGenComm() throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		
		 String dbName = "android_geo_tag";
		 Statement stmt = null;
		 ResultSet rs;
		 String query;
		 Connection con;
		 int i = 0;
		 int max = 0;
		 int ids_comm[] = new int[100000];
		 
		 Class.forName("com.mysql.jdbc.Driver").newInstance();
		 con = DriverManager.getConnection("jdbc:mysql://localhost:3306/android_geo_tag", "root", "seppiessa");
		 stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
		  
		 query = "select id_note from " + dbName + ".note" ;
		 rs = stmt.executeQuery(query);
		 
		 for( i = 0; rs.next(); i++){
		    	
				ids_comm[i] = rs.getInt("id_note");
		    }
		    
		    /* trova il massimo valore dell'id_commento nelle tabelle */
		    
		 max = ids_comm[0];
		 for (i = 1; i < ids_comm.length; i++){
			 if(ids_comm[i] > max)
				 max = ids_comm[i];
		 }
		return max + 1;
	}


	
	private int idPhotoGen()  throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException{
		
		 String dbName = "android_geo_tag";
		 Statement stmt = null;
		 ResultSet rs;
		 String query;
		 Connection con;
		 int i = 0;
		 int max = 0;
		 int ids_comm[] = new int[100000];
		 
		 Class.forName("com.mysql.jdbc.Driver").newInstance();
		 con = DriverManager.getConnection("jdbc:mysql://localhost:3306/android_geo_tag", "root", "seppiessa");
		 stmt = con.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
		  
		 query = "select id_photo from " + dbName + ".photo";
		 rs = stmt.executeQuery(query);
		 
		 for( i = 0; rs.next(); i++){
		    	
				ids_comm[i] = rs.getInt("id_photo");
		    }
		    
		    /* trova il massimo valore dell'id_commento nelle tabelle */
		    
		 max = ids_comm[0];
		 for (i = 1; i < ids_comm.length; i++){ 
			 if(ids_comm[i] > max)
				 max = ids_comm[i];
		 }
		  
		return max + 1;
		
		
	}
	
	

}
